package edu.usm.predatorwars;

import java.net.InetAddress;
import java.net.UnknownHostException;

import edu.predatorwars.shared.models.Player;
import edu.predatorwars.shared.models.PlayerConnectionInfo;
import edu.usm.predatorwars.webservice.GameHostClient;

/**
 * Convenience class to help make it easier on clients
 * to make a ClientMask
 * 
 * This builder will use the following defaults if they are not set explicitly:
 * 1. Creates and runs a local web server on port 8080
 * 2. Use GameHostClient implementation based on Jersey and its client API
 * 3. Use 'Default Player' for player name
 */
public class ClientMaskBuilder {

	private final String gameHostUrl;
	
	private GameEventProducer gameEventProducer;
	private GameHostResourceClient gameHostClient;
	private GameEventConsumer consumer;
	private String playerName;
	private String hostPort;
        private float[] playerColor;
	
	public ClientMaskBuilder(String gameHostUrl) {
		this.gameHostUrl = gameHostUrl;
	}

	public ClientMaskBuilder localWebServer(GameEventProducer webserver) {
		this.gameEventProducer = webserver;
		return this;
	}
	
	public ClientMaskBuilder gameHostResourceClient(GameHostResourceClient gameHostClient) {
		this.gameHostClient = gameHostClient;
		return this;
	}
	
	public ClientMaskBuilder gameEventConsumer(GameEventConsumer consumer) {
		this.consumer = consumer;
		return this;
	}
	
	public ClientMaskBuilder playerName(String playerName) {
		this.playerName = playerName;
		return this;
	}
        
        public ClientMaskBuilder playerColor(float[] playerColor) {
                this.playerColor = playerColor;
                return this;
        }
	
	public ClientMaskBuilder hostPort(String hostPort) {
		this.hostPort = hostPort;
		return this;
	}
	
	public ClientMask build() throws UnknownHostException {
		if (playerName == null) {
			playerName = "Default Player";
		}

		if (hostPort == null) {
			hostPort = "8080";
		}
                
                if (playerColor == null) {
                    playerColor = new float[] {0.5f,0.0f,0.2f};
                }
		
		PlayerConnectionInfo info = new PlayerConnectionInfo(playerName, getResourceUrl(hostPort));
		Player player = new Player(info,playerColor);
		
		if (consumer == null) {
			consumer = new DefaultGameEventConsumer();
		}
		
		if (gameEventProducer == null) {
			gameEventProducer = new LocalWebServerImpl(consumer, info.getIpAddress());
		}
		
		if (gameHostClient == null) {
			gameHostClient = new GameHostClient(gameHostUrl);
		}

		return new ClientMask(gameEventProducer, consumer, gameHostClient, player);
	}

	private String getResourceUrl(String hostPort) throws UnknownHostException {
		InetAddress addr = InetAddress.getLocalHost();
		return addr.getHostAddress() + ":" + hostPort;
	}
}
